from odoo import api, models, fields, _


class SaleChangeWizard(models.TransientModel):
    _name = 'sale.change.wizard'

    sale_change_apply_id = fields.Many2one('sale.change.apply')
    partner_id = fields.Many2one('res.partner', domain="[('code', '!=', False)]", string='客户')
    product_tmpl_id = fields.Many2one('product.template', string="客户部件")
    line_ids = fields.One2many('sale.change.wizard.line', 'wizard_id')

    def button_confirm(self):
        self = self.sudo()
        line_vals = []
        self.sale_change_apply_id.line_ids = None
        for line in self.line_ids:
            if not line.is_option: continue
            line_vals.append((0, 0, {
                'sale_order_id': line.sale_order_id.id,
                'order_line': line.order_line.id
            }))
        self.sale_change_apply_id.line_ids = line_vals


class SaleChangeWizardLine(models.TransientModel):
    _name = 'sale.change.wizard.line'

    wizard_id = fields.Many2one('sale.change.wizard')
    # 销售订单
    sale_order_id = fields.Many2one('sale.order', string='Sale Order')
    # 销售订单行
    order_line = fields.Many2one('sale.order.line', string='Sale Order Line')
    # 交货日期
    commitment_date = fields.Datetime(string="Commitment Date", related='sale_order_id.commitment_date')
    # 计划日期
    planned_receiving_date = fields.Datetime(string='Plan Date', related='sale_order_id.planned_receiving_date')
    # 数量
    qty = fields.Float(string='Qty', related='order_line.product_uom_qty')
    # 新增销售订单的状态, 用来对销售订单进行，取消、暂停、拆分操作
    status = fields.Selection(related='sale_order_id.status', string='Status')
    # 单价
    price_unit = fields.Float('Unit Price', related="order_line.price_unit")
    is_option = fields.Boolean(default=False, help='取消、暂停、拆分一个单据只能操作一遍')